﻿<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>兄弟组件的数据传递</title>
    <script src="js/vue.js"></script>
</head>

<body>
    <div id="app">
        <component1></component1>
        <component2></component2>
    </div>

    <template id="t1">
        <div>
            我是component1,{{attr2}}

        </div>
    </template>

    <template id="t2">
        <div>
            我是component2
            <button @click="send">将component2的数据传递给component1</button>
        </div>
    </template>

    <script>
        /***
         *   兄弟组件之间的数据通信：
         *      1.定义空Vue
         *      2.空Vue.$emit  自定义事件 以及 值
         *      3.空Vue.on 通过 "自定义事件" 获取值
         * */


        var event = new Vue({});

        var vm = new Vue({
            el: "#app",
            components: {
                "component1": {
                    template: "#t1",
                    data() {
                        return {
                            attr1: "我是component1的数据",
                            attr2: ""
                        }
                    },
                    mounted() {
                        //接收
                        event.$on("e-world", attr2 => {
                            this.attr2 = attr2;
                        });
                    },
                },
                "component2": {
                    template: "#t2",
                    data() {
                        return {
                            attr2: "我是component2的数据"
                        }
                    },
                    methods: {
                        send() {
                            //发送数据
                            event.$emit("e-world", this.attr2);
                        }
                    },
                }
            }
        });
    </script>
</body>

</html>